
"use strict";

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.default = exports.InterceptorManager = void 0;

var _utils = require("./utils");

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

var methods = ["OPTIONS", "GET", "HEAD", "POST", "PUT", "DELETE", "TRACE", "CONNECT"];

var InterceptorManager = /*#__PURE__*/function () {
    function InterceptorManager() {
        _classCallCheck(this, InterceptorManager);

        this.handlers = [];
    }

    _createClass(InterceptorManager, [{
        key: "use",
        value: function use(fulfilled, rejected) {
            this.handlers.push({
                fulfilled: fulfilled,
                rejected: rejected
            });
            return this.handlers.length - 1;
        }
    }, {
        key: "eject",
        value: function eject(id) {
            if (this.handlers[id]) {
                this.handlers[id] = null;
            }
        }
    }, {
        key: "forEach",
        value: function forEach(fn) {
            this.handlers.forEach(function (e) {
                return e && fn(e);
            });
        }
    }]);

    return InterceptorManager;
}();

exports.InterceptorManager = InterceptorManager;

var Request = /*#__PURE__*/function () {
    function Request() {
        var _this = this;

        var defaults = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

        _classCallCheck(this, Request);

        this.defaults = defaults;
        this.interceptors = {
            request: new InterceptorManager(),
            response: new InterceptorManager()
        };
        methods.forEach(function (method) {
            return _this[method.toLowerCase()] = function (url, data) {
                var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
                return _this.request(_objectSpread(_objectSpread({}, options), {}, {
                    url: url,
                    data: data,
                    method: method
                }));
            };
        });
    }

    _createClass(Request, [{
        key: "request",
        value: function request(options) {
            var _ref = [[this.dispatch.bind(this), null], Promise.resolve((0, _utils.merge)(this.defaults, options))],
                chain = _ref[0],
                promise = _ref[1];
            this.interceptors.request.forEach(function (interceptor) {
                chain.unshift(interceptor.fulfilled, null);
            });
            this.interceptors.response.forEach(function (interceptor) {
                chain.push(interceptor.fulfilled, interceptor.rejected);
            });

            while (chain.length) {
                promise = promise.then(chain.shift(), chain.shift());
            }

            return promise;
        }
    }, {
        key: "dispatch",
        value: function dispatch(params) {
            ["success", "fail"].forEach(function (item) {
                params[item] && delete params[item];
            });

            if (this.defaults.baseURL && !(0, _utils.isAbsoluteURL)(params.url)) {
                params.url = (0, _utils.combineURLs)(this.defaults.baseURL, params.url);
            }

            return new Promise(function (resolve, reject) {
                var requestTask = uni.request(_objectSpread(_objectSpread({
                    url: params.url
                }, params), {}, {
                    success: function success(res) {
                        return resolve(res);
                    },
                    fail: function fail(err) {
                        return reject(err);
                    },
                    complete: function complete(res) {
                        params.complete && params.complete(res);
                    }
                }));
                params.timeout && setTimeout(function () {
                    requestTask.abort();
                    resolve("request timeout");
                }, +params.timeout);
            });
        }
    }]);

    return Request;
}();

var createInstance = function createInstance(requestOptions) {
    var context = new Request(requestOptions),
        instance = (0, _utils.bind)(Request.prototype.request, context);
    (0, _utils.extend)(instance, Request.prototype, context);
    (0, _utils.extend)(instance, context);
    return instance;
};

const defaults = {
    // baseURL: "http://qklt.xuanhuabang.site/index.php",
    baseURL: "http://qkl.xuanhuabang.site/index.php",
    dataType: "json",
    header: {
        "Content-type": "application/x-www-form-urlencoded"
    },
    responseType: "text"
};

var request = createInstance(defaults);

request.create = function (options) {
    return createInstance(Object.assign(defaults, options));
};

request.interceptors.request.use(
    params => {
        params.data || (params.data = {});
        params.data.token = _utils.Storage.get("token");

        for (const key in params.data) {
            if ([undefined, null, NaN].includes(params.data && params.data[key])) {
                delete params?.data[key];
            }
        }
        return params;
    }
);

request.interceptors.response.use(
    res => {
        const { code, msg: title } = res.data;

        console.warn(res.data);

        switch (+code) {
            case 1:
            case 302:
                return Promise.resolve(res.data);
            case 300:
                uni.showToast({ title, icon: "none" });
                uni.reLaunch({ url: "/pages/loginReg/login" });
                return Promise.reject(res.data);
            default:
                uni.showToast({ title, icon: "none" })
                return Promise.reject(res.data);
        }
    },
    err => {
        uni.showToast({ title: `网络请求失败\n您可以在“设置”中为此App打开无线局域网`, icon: "none", duration: 3000 })
        return Promise.reject(err)
    }
);

exports.default = request;
